import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Modal,
  Form,
  Select,
  message,
  Tag,
  Tooltip,
  Upload,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import type { Teacher } from "../../../types/admin";
import { useUser } from "../../../contexts/UserContext";
import { adminAPI } from "../../../services/api";
import PermissionGuard from "../../../components/PermissionGuard";
import FileUpload from "../../../components/FileUpload";

const { Search } = Input;
const { confirm } = Modal;

const TeacherManagement: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [teachers, setTeachers] = useState<Teacher[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingTeacher, setEditingTeacher] = useState<Teacher | null>(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState("");

  // 获取教师列表
  const fetchTeachers = async (params?: any) => {
    try {
      setLoading(true);
      console.log("👥 获取教师列表...", params);

      // 使用写死的数据，不调用API
      await new Promise((resolve) => setTimeout(resolve, 300)); // 模拟加载延迟
      
      // 生成20个教师的mock数据
      const teacherNames = [
        "王峰华", "李志强", "张明远", "刘建国", "陈志伟", "杨建华", "赵德明", "黄志强", "周建军", "吴国强",
        "徐志强", "孙建华", "马志强", "朱建国", "胡志强", "郭建华", "何志强", "高建国", "林志强", "罗建华"
      ];
      
      const departments = [
        "计算机学院", "数学学院", "物理学院", "外语学院", "电子工程学院", "机械工程学院", "经济管理学院"
      ];
      
      const titles = ["教授", "副教授", "讲师"];
      
      const courseLists = [
        ["高等数学", "线性代数", "概率论"],
        ["大学英语", "英语口语", "英语写作"],
        ["Python程序设计", "Java程序设计", "数据结构与算法"],
        ["操作系统原理", "计算机网络", "数据库原理"],
        ["机器学习", "深度学习", "人工智能导论"],
        ["大学物理", "物理实验", "工程力学"],
        ["经济学原理", "管理学原理", "市场营销"]
      ];

      const mockTeachers: Teacher[] = teacherNames.map((name, index) => ({
        id: `t${index + 1}`,
        name,
        email: `${name.toLowerCase()}@xht-teach.com`,
        phone: `138${String(index + 1).padStart(8, '0')}`,
        department: departments[index % departments.length],
        title: titles[index % titles.length],
        status: index === 15 ? "inactive" : "active", // 第16个教师设为非活跃
        courses: courseLists[index % courseLists.length],
        createTime: `2024-01-${String(index + 10).padStart(2, '0')}`,
      }));

      // 如果有搜索参数，进行过滤
      let filteredTeachers = mockTeachers;
      if (params?.search) {
        const searchText = params.search.toLowerCase();
        filteredTeachers = mockTeachers.filter(
          teacher =>
            teacher.name.toLowerCase().includes(searchText) ||
            teacher.email.toLowerCase().includes(searchText) ||
            teacher.department.toLowerCase().includes(searchText) ||
            teacher.title.toLowerCase().includes(searchText)
        );
      }

      setTeachers(filteredTeachers);
      console.log("✅ 获取教师列表成功:", filteredTeachers.length + "条记录");
    } catch (error) {
      console.error("❌ 获取教师列表失败:", error);
      message.error("获取教师列表失败，请检查网络连接");
      setTeachers([]);
    } finally {
      setLoading(false);
    }
  };

  // 创建教师
  const createTeacher = async (data: any) => {
    try {
      console.log("➕ 创建教师...", data);

      // 模拟创建成功
      await new Promise((resolve) => setTimeout(resolve, 200));
      
      message.success("创建教师成功");
      fetchTeachers(); // 重新获取列表
      return true;
    } catch (error) {
      console.error("❌ 创建教师失败:", error);
      message.error("创建教师失败");
      return false;
    }
  };

  // 更新教师
  const updateTeacher = async (id: string, data: any) => {
    try {
      console.log("📝 更新教师...", id, data);

      // 模拟更新成功
      await new Promise((resolve) => setTimeout(resolve, 200));
      
      message.success("更新教师信息成功");
      fetchTeachers(); // 重新获取列表
      return true;
    } catch (error) {
      console.error("❌ 更新教师失败:", error);
      message.error("更新教师信息失败");
      return false;
    }
  };

  // 删除教师
  const deleteTeacher = async (id: string) => {
    try {
      console.log("🗑️ 删除教师...", id);

      // 模拟删除成功
      await new Promise((resolve) => setTimeout(resolve, 200));
      
      message.success("删除教师成功");
      fetchTeachers(); // 重新获取列表
      return true;
    } catch (error) {
      console.error("❌ 删除教师失败:", error);
      message.error("删除教师失败");
      return false;
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchTeachers();
  }, []);

  const handleSearch = (value: string) => {
    setSearchText(value);
    // 调用API进行搜索
    fetchTeachers({ search: value });
  };

  const handleImportCSV = async (file: File) => {
    try {
      setLoading(true);
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const text = e.target?.result as string;
          const rows = text.split("\n").filter((row) => row.trim());

          if (rows.length < 2) {
            message.error("文件格式错误，至少需要包含标题行和数据行");
            return;
          }

          const headers = rows[0].split(",");
          const teachers = rows
            .slice(1)
            .map((row) => {
              const values = row.split(",");
              return {
                name: values[0]?.trim(),
                email: values[1]?.trim(),
                phone: values[2]?.trim(),
                department: values[3]?.trim(),
                title: values[4]?.trim(),
                status: "active",
              };
            })
            .filter((teacher) => teacher.name && teacher.email); // 过滤无效数据

          // 批量创建教师
          console.log("📤 批量导入教师...", teachers.length + "条记录");

          let successCount = 0;
          let failCount = 0;

          for (const teacher of teachers) {
            try {
              const success = await createTeacher(teacher);
              if (success) {
                successCount++;
              } else {
                failCount++;
              }
              // 添加小延迟，避免请求过于频繁
              await new Promise((resolve) => setTimeout(resolve, 100));
            } catch (error) {
              failCount++;
            }
          }

          message.success(
            `导入完成：成功 ${successCount} 条，失败 ${failCount} 条`
          );
        } catch (error) {
          console.error("❌ 解析CSV文件失败:", error);
          message.error("解析文件失败，请检查文件格式");
        }
      };
      reader.readAsText(file);
    } catch (error) {
      console.error("❌ 导入文件失败:", error);
      message.error("导入失败，请检查文件格式");
    } finally {
      setLoading(false);
    }
  };

  const showEditModal = (teacher: Teacher | null) => {
    setEditingTeacher(teacher);
    setModalVisible(true);
    if (teacher) {
      form.setFieldsValue(teacher);
    } else {
      form.resetFields();
    }
  };

  const handleDelete = (id: string) => {
    confirm({
      title: "确认删除",
      icon: <ExclamationCircleOutlined />,
      content: "确定要删除这位教师吗？此操作不可恢复。",
      onOk: async () => {
        try {
          await deleteTeacher(id);
        } catch (error) {
          message.error("删除失败");
        }
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingTeacher) {
        await updateTeacher(editingTeacher.id, values);
      } else {
        await createTeacher(values);
      }
      setModalVisible(false);
    } catch (error) {
      message.error("提交失败");
    }
  };

  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "院系",
      dataIndex: "department",
      key: "department",
    },
    {
      title: "职称",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Tag color={status === "active" ? "green" : "red"}>
          {status === "active" ? "在职" : "离职"}
        </Tag>
      ),
    },
    {
      title: "课程数",
      dataIndex: "courses",
      key: "courses",
      render: (courses: string[]) => (
        <Tooltip title={courses.join(", ")}>
          <Tag color="blue">{courses.length}</Tag>
        </Tooltip>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: Teacher) => (
        <Space>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PermissionGuard permission="teacher.manage">
      <div style={{ padding: "24px" }}>
        <Card>
          <Space direction="vertical" style={{ width: "100%" }}>
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => showEditModal(null)}
              >
                添加教师
              </Button>
              <Search
                placeholder="搜索教师..."
                onSearch={handleSearch}
                style={{ width: 300 }}
              />
              <FileUpload onUpload={handleImportCSV} buttonText="批量导入" />
              <Tooltip title="下载模板">
                <Button icon={<UploadOutlined />}>下载导入模板</Button>
              </Tooltip>
            </Space>

            <Table
              rowKey="id"
              columns={columns}
              dataSource={teachers}
              loading={loading}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </Space>
        </Card>

        <Modal
          title={editingTeacher ? "编辑教师" : "添加教师"}
          open={modalVisible}
          onOk={handleModalOk}
          onCancel={() => setModalVisible(false)}
          destroyOnClose
        >
          <Form form={form} layout="vertical">
            <Form.Item
              name="name"
              label="姓名"
              rules={[{ required: true, message: "请输入姓名" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: "请输入邮箱" },
                { type: "email", message: "请输入有效的邮箱地址" },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="phone"
              label="电话"
              rules={[{ required: true, message: "请输入电话" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="department"
              label="院系"
              rules={[{ required: true, message: "请输入院系" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="title"
              label="职称"
              rules={[{ required: true, message: "请选择职称" }]}
            >
              <Select>
                <Select.Option value="教授">教授</Select.Option>
                <Select.Option value="副教授">副教授</Select.Option>
                <Select.Option value="讲师">讲师</Select.Option>
                <Select.Option value="助教">助教</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: "请选择状态" }]}
            >
              <Select>
                <Select.Option value="active">在职</Select.Option>
                <Select.Option value="inactive">离职</Select.Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PermissionGuard>
  );
};

export default TeacherManagement;
